package design.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
 * 享元模式：使用共享对象可以有效地支持大量的细粒度的对象。
 * 细粒度：区分一个对象的内部状态和外部状态，通过外部状态唯一标识一个对象，防止重复对象更多
 */
public class Flyweight {
    //内部状态，可以共享的信息，存储在对象内部并且不会随环境改变
    private String mIntrinsic;
    //外部状态，不可以共享的信息，随着环境的改变而改变，是对象的索引值
    protected final String mExtrinsic;

    public Flyweight(String extrinsic) {
        this.mExtrinsic = extrinsic;
    }
}

class ConcreateFlyweight extends Flyweight {
    public ConcreateFlyweight(String extrinsic) {
        super(extrinsic);
    }
}

class FlyweightFactory {
    //容器
    private static Map<String, Flyweight> map = new HashMap<>();

    public static Flyweight build(String extrinsic) {
        Flyweight flyweight = null;
        if (map.containsKey(extrinsic)) {
            flyweight = map.get(extrinsic);
        } else {
            flyweight = new ConcreateFlyweight(extrinsic);
            map.put(extrinsic, flyweight);
        }
        return flyweight;
    }
}
